package repositories

import (
	"pass-tree/internal/logic/models"
)

func GetInputContent(password_id int) ([]models.Input_content, error) {
	ret, err := DB.Query("select * from input_content where password_id=?", password_id)
	if err != nil {
		return nil, err
	}
	var cs []models.Input_content
	for ret.Next() {
		var cat models.Input_content
		_ = ret.Scan(&cat.Id, &cat.Password_id, &cat.Input_type, &cat.Content)
		cs = append(cs, cat)
	}
	return cs, nil
}

func SaveInputContent(input models.Input_content) error {
	ret, err := DB.Exec("insert into input_content (password_id,input_type,content) values (?,?,?)", input.Password_id, input.Input_type, input.Content)
	if err != nil {
		return err
	}
	lastInsertId, err := ret.LastInsertId()
	if err != nil {
		return err
	}
	input.Id = int(lastInsertId)
	return nil
}

// 批量插入数据
func BatchSaveInputContent(input []models.Input_content) error {
	// 准备基础插入语句
	query := "insert into input_content (password_id,input_type,content) values "

	// 准备值部分
	var values []interface{}
	for i, v := range input {
		if i > 0 {
			query += ", "
		}
		query += "(?, ?, ?)"
		values = append(values, v.Password_id, v.Input_type, v.Content)
	}
	_, err := DB.Exec(query, values...)
	if err != nil {
		return err
	}
	return nil
}

func UpdateInputContent(input *models.Input_content) error {
	ret, err := DB.Exec("update input_content set content=? where id=?", input.Content, input.Id)
	if err != nil {
		return err
	}
	lastInsertId, err := ret.LastInsertId()
	if err != nil {
		return err
	}
	input.Id = int(lastInsertId)
	return nil
}

func DeleteInputContent(id int) error {
	ret, err := DB.Exec("delete from input_content where id=?", id)
	if err != nil {
		return err
	}
	_, err = ret.RowsAffected()
	if err != nil {
		return err
	}
	return nil
}
